package com.ybg.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;


/**
 * 系统参数工具类
 * 
 * @author zhouqixin
 */
public class SysParamUtil {
	private static Map<String, Object> Simple_Params = new HashMap<String, Object>();

	public static void init(JdbcTemplate jdbcTemplate) {
		List<Map<String, Object>> sysList = jdbcTemplate.queryForList("select paramkey, paramvalue from system_config");

		for (int i = 0; i < sysList.size(); i++) {
			Simple_Params.put(sysList.get(i).get("paramkey") + "", sysList.get(i).get("paramvalue"));
		}
		
		LogUtil.debug("Simple_Params: {}", Simple_Params);
	}

	/**
	 * 从数据库获取系统参数
	 * 
	 * @param jdbcTemplate
	 * @param key
	 * @return
	 */
	public static String getNewSimpleConfigValue(JdbcTemplate jdbcTemplate, String key) {
		String resultString = null;
		try {
			resultString = jdbcTemplate.queryForObject("select paramvalue from system_config where paramkey=?", new Object[] { key }, String.class);
			Simple_Params.put(key, resultString);
		} catch(DataAccessException e) {
			LogUtil.error("{} is not exist!", key);
			return null;
		}
		return resultString;
	}
	
	/**
	 * 从缓存获取系统参数
	 * 
	 * @param key
	 * @return
	 */
	public static String getSimpleConfigValue(String key) {
		if (Simple_Params.containsKey(key)) {
			return (String) Simple_Params.get(key);
		} else {
			LogUtil.error("{} is not exist in cache!", key);
			return null;
		}
	}
	
	/**
	 * 从缓存获取系统参数，如果没有则从数据库中查询
	 * 
	 * @param jdbcTemplate
	 * @param key
	 * @return
	 */
	public static String getSimpleConfigValue(JdbcTemplate jdbcTemplate, String key) {
		if (Simple_Params.containsKey(key)) {
			return (String) Simple_Params.get(key);
		} else {
			return getNewSimpleConfigValue(jdbcTemplate, key);
		}
	}
}